<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="../../css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="../../css/header.css" />
		<link rel="stylesheet" type="text/css" href="../../css/chat.css" />
		<style>
			html,
			body {
				height: 100%;
				margin: 0px;
				padding: 0px;
				overflow: hidden;
				-webkit-touch-callout: none;
				-webkit-user-select: none;
			}
		</style>
	</head>

	<body contextmenu="return false;">
		<header class="mui-bar mui-bar-nav title" style="position: fixed;">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left title-color" id="btn_goto_chat"></a>
			<span class="mui-title title-color" style="text-align: left; margin-top: 2px;" id="chatting-nickname">雨 信</span>
		</header>

		<div id="msg-outter" class="mui-content">
			<div id='msg'>

			</div>
		</div>

		<footer>
			<div class="footer-center">
				<textarea id='input_message' type="text" class='input-text'></textarea>
			</div>
			<label for="" class="footer-right">
				<button type="button" class="mui-btn mui-btn-gray" id="btn_send">发送</button>
			</label>
		</footer>

		<script src="../../js/mui.min.js"></script>
		<script type="application/javascript" src="../../js/app.js"></script>
		<script type="text/javascript">
			// 创建命名空间，只需要把自己的代码，写进入，那么外部就无法访问
			//			(function($, doc){

			mui.init();
			// 获取上一个页面传入的好友属性值
			var friendUserId;
			var friendNickname;
			var friendThumHeadPortrait;
			mui.plusReady(function() {
				// 获取我自己的用户信息					
				var user = app.getUserGlobalInfo();
				// 获取聊天页面webview
				var currentWebview = plus.webview.currentWebview();
				// 设置聊天页面的软键盘样式
				currentWebview.setStyle({
					softinputMode: "adjustResize"
				});

				// 获取上一个页面传入的好友属性值
				friendUserId = currentWebview.friendUserId;
				friendNickname = currentWebview.friendNickname;
				friendThumHeadPortrait = currentWebview.friendThumHeadPortrait;
				if (!friendThumHeadPortrait) {
					friendThumHeadPortrait = '../../image/face-default-cat.png'
				} else {
					friendThumHeadPortrait = app.fileServerUrl + friendThumHeadPortrait;
				}

				// 标题改为朋友的昵称
				document.getElementById("chatting-nickname").innerHTML = friendNickname;

				// 渲染初始化的聊天记录HTML
				var chatingWebview = plus.webview.currentWebview();
				chatingWebview.addEventListener("show", function() {
					initChatHistory();
				});

				var areaMsgList = document.getElementById("msg");
				// 设置聊天记录进入页面的时候自动滚动到最后一条
				areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;

				// 获取dom控件
				var inputMessage = document.getElementById("input_message");
				var btnSend = document.getElementById("btn_send");

				// 监听用户输入，使得send按钮变色
				inputMessage.addEventListener("input", function() {
					var msg_text_val = inputMessage.value;
					if (msg_text_val.length > 0) {
						btnSend.setAttribute("class", "mui-btn-green");
					} else {
						btnSend.setAttribute("class", "mui-btn-gray");
					}
				});

				// 对当前的窗口监听resize事件
				window.addEventListener("resize", function() {
					resizeScreen();
					document.getElementById("msg-outter").style.paddingBottom = "50px";
				});

				// 回到聊天列表页面
				var btn_goto_chat = document.getElementById("btn_goto_chat");
				btn_goto_chat.addEventListener("tap", function() {
					currentWebview.close();
					var indexWebview = plus.webview.getWebviewById("index.html");
					indexWebview.evalJS("showChatPage(0)");
				});

				// 发送消息按钮的事件绑定
				btnSend.addEventListener("tap", function() {
					// 发送之前判断网络的状态
					var connectionStatus = plus.networkinfo.getCurrentType();
					console.log("connectionStatus: " + connectionStatus)
					if (connectionStatus == 0 || connectionStatus == 1) {
						app.showToast("请打开网络连接...", "error");
						return;
					}

					// 获取消息内容
					var messageValue = inputMessage.value;

					// 判断消息内容，如果长度等于0，则return
					if (!messageValue.length) {
						return;
					}

					// 发送消息, 渲染消息的html到msg div之下
					sendMsg(user.thumHeadPortrait, messageValue);
					// 情况消息文本框中的内容
					inputMessage.value = "";
					// 发送消息完毕之后，把发送按钮的颜色改为灰白色
					btnSend.setAttribute("class", "mui-btn-gray");

					// 构建messageData
					var messageData = {
						header: {
							messageType: app.CHAT,
							sendUserId: user.id,
							receiveUserId: friendUserId
						},
						body: {
							message: messageValue
						},
						extension: {}
					};
					// 调用websocket 发送消息到服务器
					var indexWebview = plus.webview.getWebviewById("index.html");
					indexWebview.evalJS("chat.sendMessage('" + JSON.stringify(messageData) + "')");
					var chatHistory = {
						ownerId: user.id,
						otherId: friendUserId,
						message: messageValue,
						type: 1
					}
					// 保存聊天历史记录到本地缓存
					app.saveOneChatHistory(chatHistory);
					// 保存聊天快照记录到本地缓存
					chatHistory.isRead = true;
					app.saveOneChatSnapshot(chatHistory, user.id);
					// 刷新消息列表
					var chatWebview = plus.webview.getWebviewById("chat.html");
					chatWebview.evalJS("loadingChatSnapshot()");
				});
			});

			// 接收消息
			function receiveMsg(msg) {
				var msgHtml = '<div class="friend_lists">' +
					'<div class="header_img">' +
					'<img src="' + friendThumHeadPortrait + '" width="40px" height="40px" />' +
					'</div>' +
					'<div class="msg-wrapper right">' +
					'<p class="msg-left-white">' + msg + '</p>' +
					'</div>' +
					'</div>';

				var msg_list = document.getElementById("msg");
				msg_list.insertAdjacentHTML("beforeend", msgHtml);

				// playReceiveMsgSound();
			}

			// 发送消息
			function sendMsg(faceImg, msg) {
				var msgHtml = '<div class="me_lists">' +
					'<div class="header_img">' +
					'<img src="' + faceImg + '" width="40px" height="40px" />' +
					'</div>' +
					'<div class="msg-wrapper left">' +
					'<p class="msg-right-green">' + msg + '</p>' +
					'</div>' +
					'</div>';
				var msg_list = document.getElementById("msg");
				msg_list.insertAdjacentHTML("beforeend", msgHtml);

				// playSendMsgSound();
			}

			// 播放发送消息的铃声
			function playSendMsgSound() {
				var audioPlayer = plus.audio.createPlayer("/mp3/send.mp3");
				audioPlayer.play();
			}

			// 播放接受消息的铃声
			function playReceiveMsgSound() {
				var audioPlayer = plus.audio.createPlayer("/mp3/di_didi.mp3");
				audioPlayer.play();
			}

			// 重新调整聊天窗口
			function resizeScreen() {
				var areaMsgList = document.getElementById("msg");
				// 设置聊天记录进入页面的时候自动滚动到最后一条
				areaMsgList.scrollTop = areaMsgList.scrollHeight + areaMsgList.offsetHeight;
			};

			//			}(mui, document));

			// 初始化用户的聊天记录
			function initChatHistory() {
				var msg_list = document.getElementById("msg");

				var user = app.getUserGlobalInfo();
				var userId = user.id;
				var thumHeadPortrait = user.thumHeadPortrait;
				if (!thumHeadPortrait) {
					thumHeadPortrait = '../../image/face-default-cat.png'
				} else {
					thumHeadPortrait = app.fileServerUrl + thumHeadPortrait;
				}
				var chatHistoryList = app.getChatHistory(userId, friendUserId);

				var togetherHTML = "";

				for (var i = 0; i < chatHistoryList.length; i++) {
					var chatHistory = chatHistoryList[i];
					if (chatHistory.type == 1) {
						togetherHTML += '<div class="me_lists">' +
							'<div class="header_img">' +
							'<img src="' + thumHeadPortrait + '" width="40px" height="40px" />' +
							'</div>' +
							'<div class="msg-wrapper left">' +
							'<p class="msg-right-green">' + chatHistory.message + '</p>' +
							'</div>' +
							'</div>';
					} else {
						togetherHTML += '<div class="friend_lists">' +
							'<div class="header_img">' +
							'<img src="' + friendThumHeadPortrait + '" width="40px" height="40px" />' +
							'</div>' +
							'<div class="msg-wrapper right">' +
							'<p class="msg-left-white">' + chatHistory.message + '</p>' +
							'</div>' +
							'</div>';
					}
				}
				msg_list.innerHTML = togetherHTML;
			}
		</script>
	</body>

</html>
